package com.dandelion.common.utils;

import com.dandelion.common.http.HttpContext;
import com.rockit.core.exception.BadCredentialsException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

public class ValidateUtils {
    public static void assertNoError(BindingResult bindingResult) {
        if (bindingResult == null || !bindingResult.hasErrors()) {
            return;
        }

        FieldError error = bindingResult.getFieldError();
        throw new IllegalArgumentException(error.getDefaultMessage());
    }

    public static void checkLogin() {
        if (HttpContext.current().getUserId() <= 0) {
            throw new BadCredentialsException();
        }
    }

    public static boolean isLogin() {
        return (HttpContext.current().getUserId() > 0);
    }

    public static void noErrorAndIsLogin(BindingResult bindingResult) {
        checkLogin();
        assertNoError(bindingResult);
    }

    public static boolean isValidUserId(Long userId) {
        return userId != null && userId > 0;
    }

    public static boolean isInvalidUserId(Long userId) {
        return userId == null || userId <= 0;
    }
}
